<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑法规' : '新增法规'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="法规名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入法规名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法规编号" prop="number">
            <el-input v-model="form.number" placeholder="请输入法规编号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="法规类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择法规类型" style="width: 100%">
              <el-option label="国家法律" value="national_law" />
              <el-option label="行政法规" value="administrative_regulation" />
              <el-option label="部门规章" value="departmental_rule" />
              <el-option label="地方法规" value="local_regulation" />
              <el-option label="技术标准" value="technical_standard" />
              <el-option label="管理制度" value="management_system" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发布机构" prop="publisher">
            <el-input v-model="form.publisher" placeholder="请输入发布机构" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发布日期" prop="publishDate">
            <el-date-picker
              v-model="form.publishDate"
              type="date"
              placeholder="请选择发布日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="form.effectiveDate"
              type="date"
              placeholder="请选择生效日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="生效中" value="active" />
              <el-option label="待审核" value="pending" />
              <el-option label="已失效" value="expired" />
              <el-option label="已废止" value="abolished" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重要程度">
            <el-switch
              v-model="form.isImportant"
              active-text="重要"
              inactive-text="普通"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="法规摘要" prop="summary">
        <el-input
          v-model="form.summary"
          type="textarea"
          :rows="3"
          placeholder="请输入法规摘要"
        />
      </el-form-item>

      <el-form-item label="法规内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="请输入法规详细内容"
        />
      </el-form-item>

      <el-form-item label="关键词">
        <el-input
          v-model="form.keywords"
          placeholder="请输入关键词，多个关键词用逗号分隔"
        />
      </el-form-item>

      <el-form-item label="附件上传">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
          :auto-upload="false"
          :file-list="fileList"
          @change="handleFileChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 pdf、doc、docx 格式文件，单个文件大小不超过 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

// Props
interface Props {
  modelValue: boolean
  regulation?: any
}

const props = withDefaults(defineProps<Props>(), {
  regulation: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 响应式数据
const formRef = ref()
const submitting = ref(false)
const fileList = ref([])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.regulation?.id)

// 表单数据
const form = reactive({
  name: '',
  number: '',
  type: '',
  publisher: '',
  publishDate: '',
  effectiveDate: '',
  status: 'pending',
  isImportant: false,
  summary: '',
  content: '',
  keywords: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入法规名称', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入法规编号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择法规类型', trigger: 'change' }
  ],
  publisher: [
    { required: true, message: '请输入发布机构', trigger: 'blur' }
  ],
  publishDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择生效状态', trigger: 'change' }
  ],
  summary: [
    { required: true, message: '请输入法规摘要', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入法规内容', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    number: '',
    type: '',
    publisher: '',
    publishDate: '',
    effectiveDate: '',
    status: 'pending',
    isImportant: false,
    summary: '',
    content: '',
    keywords: '',
    remark: ''
  })
  fileList.value = []
  formRef.value?.clearValidate()
}

// 监听regulation变化，初始化表单
watch(() => props.regulation, (newVal) => {
  if (newVal) {
    Object.assign(form, {
      name: newVal.name || '',
      number: newVal.number || '',
      type: newVal.type || '',
      publisher: newVal.publisher || '',
      publishDate: newVal.publishDate || '',
      effectiveDate: newVal.effectiveDate || '',
      status: newVal.status || 'pending',
      isImportant: newVal.isImportant || false,
      summary: newVal.summary || '',
      content: newVal.content || '',
      keywords: newVal.keywords || '',
      remark: newVal.remark || ''
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 文件变化处理
const handleFileChange = (file: any, files: any[]) => {
  fileList.value = files
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.upload-demo {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>